﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Slippor.Common.PluginFramework;

namespace Slippor.Douban.Radio.BaseForm.CustomControls
{
    public partial class PluginItem : UserControl
    {
        readonly PluginInfo _pInfo;
        readonly PluginManager _pluginManager;

        public PluginItem(PluginInfo pInfo, PluginManager pManager)
        {
            InitializeComponent();

            _pInfo = pInfo;
            _pluginManager = pManager;
            linkLabelPlugin.Text = _pInfo.DisplayName;
            checkBoxEnabled.Checked = _pInfo.IsEnabled;
            linkLabelPlugin.Enabled = _pInfo.IsEnabled && _pInfo.IsConfigable;
            if (_pInfo.IsConfigable)
            {
                linkLabelPlugin.LinkBehavior = LinkBehavior.AlwaysUnderline;
            }
            else
            {
                linkLabelPlugin.LinkBehavior = LinkBehavior.NeverUnderline;
            }
            checkBoxEnabled.CheckStateChanged += new EventHandler(ToolStripPluginItem_CheckStateChanged);
        }

        private void ToolStripPluginItem_CheckStateChanged(object sender, EventArgs e)
        {
            if (_pInfo != null && _pInfo.IsEnabled != (checkBoxEnabled.CheckState == CheckState.Checked))
            {
                _pInfo.IsEnabled = checkBoxEnabled.CheckState == CheckState.Checked;
                linkLabelPlugin.Enabled = _pInfo.IsEnabled && _pInfo.IsConfigable;
                _pluginManager.UpdatePlugin(_pInfo);
            }
        }

        private void linkLabelPlugin_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (_pInfo != null)
            {
                var plugin = _pluginManager.GetPluginInstance(_pInfo);
                if (plugin != null)
                {
                    if (_pInfo.Config(ref plugin))
                    {
                        _pluginManager.ReloadPlugin(_pInfo);
                    }
                }
            }
        }
    }
}
